package ui.forms;

import base.*;
import db.*;
import java.io.IOException;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;
import utils.DateUtils;

import com.sun.lwuit.*;
import com.sun.lwuit.events.*;
import com.sun.lwuit.layouts.*;

import com.java4less.rchart.Chart;
import com.java4less.rchart.ChartAdapter;
import com.java4less.rchart.ChartListener;
import com.java4less.rchart.ChartLoader;
import com.java4less.rchart.gc.GraphicsProvider;
import com.java4less.rchart.lwuit.ChartViewer;
import com.java4less.rchart.util.Formats;
import com.sun.lwuit.geom.Dimension;
import java.util.Date;
import java.util.Vector;

/**
 * Displays the intake information of the user on a weekly basis for a particular month
 *
 * @author Shayan
 */
public class ViewReportForm extends Form implements ActionListener {

    private String[] weekDays = new String[]{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    String selDate = new String();
    private Command cmdBack;
    private Button btnNextWeek;
    private Button btnPreviousWeek;
    private Container cntButtons;
    ChartViewer chartCanvas;
    ChartLoader loader;
    Date startingDay;
    ChartAdapter chartAdapterRealtime;

    public ViewReportForm(final Form parent) {
        startingDay = DateUtils.addDays(new Date(), -7);

        cmdBack = new Command("Back") {

            public void actionPerformed(ActionEvent evt) {
                parent.showBack();
            }
        };
        addCommand(cmdBack);
        setBackCommand(cmdBack);

        setLayout(new BorderLayout());

        GraphicsProvider.setMode(GraphicsProvider.MODE_LWUIT);
        chartCanvas = new ChartViewer();
        chartCanvas.setPreferredSize(new Dimension(200, 200));

        rebuildChart();
        addComponent(BorderLayout.CENTER, chartCanvas);

        btnNextWeek = new Button("Next Week");
        btnNextWeek.addActionListener(this);

        btnPreviousWeek = new Button("Prev. Week");
        btnPreviousWeek.addActionListener(this);

        cntButtons = new Container(new BorderLayout());
        cntButtons.addComponent(BorderLayout.EAST, btnNextWeek);
        cntButtons.addComponent(BorderLayout.WEST, btnPreviousWeek);
        addComponent(BorderLayout.SOUTH, cntButtons);

        repaint();
    }
    java.util.Calendar cal = java.util.Calendar.getInstance();

    public void actionPerformed(ActionEvent evt) {
        if (evt.getSource() == btnNextWeek) {
            gotoNextWeek();
        }

        if (evt.getSource() == btnPreviousWeek) {
            gotoPreviousWeek();
        }
    }

    private void gotoNextWeek() {
        startingDay = DateUtils.addDays(startingDay, 7);
        rebuildChart();
    }

    private void gotoPreviousWeek() {
        startingDay = DateUtils.addDays(startingDay, -7);
        rebuildChart();
    }

    private void loadChartData() {
        ChartLoader chartLoader = new ChartLoader();
        chartLoader.clearParams();

        chartLoader.setParameter("YSCALE_MIN", "0");
        chartLoader.setParameter("TICK_INTERVALY", "2");
        chartLoader.setParameter("BIG_TICK_INTERVALX", "1");
        chartLoader.setParameter("YAXIS_AUTO_TICKS", "5");
        chartLoader.setParameter("XAXIS_START_WITH_BIG_TICK", "false");
        chartLoader.setParameter("YAXIS_START_WITH_BIG_TICK", "false");
        chartLoader.setParameter("XAXIS_GRID", "0.2|WHITE|DASHED");
        chartLoader.setParameter("YAXIS_GRID", "0.2|0xffffff|DASHED");
        chartLoader.setParameter("SERIE_1", "Total calories");

        chartLoader.setParameter("SERIE_TYPE_1", "BAR");

        chartLoader.setParameter("SERIE_FONT_1", "Arial|PLAIN|7");
        chartLoader.setParameter("SERIE_COLOR_1", "RED");
        chartLoader.setParameter("SERIE_STYLE_1", "2|GREEN|LINE");
        chartLoader.setParameter("SERIE_POINT_1", "true");
        chartLoader.setParameter("SERIE_POINT_COLOR_1", "RED");
        chartLoader.setParameter("LEGEND_POSITION", "BOTTOM");
        chartLoader.setParameter("XAXIS_DATE_FORMAT", "dd");
        chartLoader.setParameter("XAXIS_DATE_STEP", "d");

        chartLoader.setParameter("XAXIS_INITIAL_DATE", Formats.formatDate(DateUtils.addDays(startingDay,-2), "dd/MM/yyyy"));
        chartLoader.setParameter("TITLECHART", Formats.formatDate(startingDay, "MMM yyyy"));

        System.out.println("startingDate:" + startingDay);
        loader = chartLoader;

        String data = "";
        Date day = startingDay;
        for (int i = 0; i < 7; i++) {
            data = data + getTotalCaloriesForDay(day);
            if (i < 6) {
                data = data + "|";
            }
            day = DateUtils.getNextDay(day);
        }
        System.out.println(data);
        loader.setParameter("SERIE_DATA_1", data);
        //loader.setParameter("XLABEL", "Week " + startingDay.toString());
    }

    private void rebuildChart() {
        loadChartData();
        Chart c = loader.build(false, false);
        chartCanvas.setChart(c);
        chartCanvas.repaintChart();
    }
//    static float[] mockData = new float[]{
//        1000f, 1010f, 1020f, 1030f, 1040f, 1050f, 1060f,
//        1070f, 1080f, 1090f, 1100f, 1110f, 1120f, 1130f,
//        1140f, 1150f, 1160f, 1170f, 1180f, 1190f, 1200f};

    private String getTotalCaloriesForDay(Date day) {
        try {
            Vector dailyIntakes = IntakeManager.getDailyIntakes(Context.currentUser.getId(), day);
            if (dailyIntakes.isEmpty()) {
                System.out.println(day + "-> (0)");

                return "0";//"null";
            }
            float totalCalories = 0f;
            for (int i = 0; i < dailyIntakes.size(); i++) {
                Intake intake = (Intake) dailyIntakes.elementAt(i);
                totalCalories += intake.getCalories();
            }
            System.out.println(day + "-> " + totalCalories);
            return Formats.formatNumber(totalCalories, "0.0") ;
//            long now = DateUtils.getStartOfDay(new Date()).getTime();
//            int distance = (int) ((DateUtils.getStartOfDay(day).getTime() - now) / 86400000);
//            return mockData[distance];
        } catch (Exception ex) {
            ex.printStackTrace();
            Dialog.show("Error", ex.toString(), "OK", "");
            return "0";//"null";
        }
    }
}
